package com.lingnan.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingnan.entity.po.ChatMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {
    @Select("SELECT * FROM chat_message " +
            "WHERE session_id = #{sessionId} " +
            "ORDER BY created_at DESC " +
            "LIMIT #{limit}")
    List<ChatMessage> getRecentMessages(@Param("sessionId") Long sessionId,
                                        @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM chat_message " +
            "WHERE receiver_id = #{receiverId} " +
            "AND receiver_type = #{receiverType} " +
            "AND is_read = false")
    int countUnreadMessages(@Param("receiverId") Long receiverId,
                            @Param("receiverType") Integer receiverType);

    @Update("UPDATE chat_message SET is_read = true " +
            "WHERE session_id = #{sessionId} " +
            "AND receiver_id = #{receiverId} " +
            "AND receiver_type = #{receiverType} " +
            "AND is_read = false")
    int markMessagesAsRead(@Param("sessionId") Long sessionId,
                           @Param("receiverId") Long receiverId,
                           @Param("receiverType") Integer receiverType);

    @Select("SELECT * FROM chat_message " +
            "WHERE session_id = #{sessionId} " +
            "ORDER BY created_at ASC") // 按时间升序
    List<ChatMessage> getHistoryMessages(@Param("sessionId") Long sessionId);
}